// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.appengine.preferencessync.internal;

import com.google.appengine.syncserver.shared.PropertyChange;

import java.util.ArrayList;

/**
 * Class for paging request to the server.
 */
public class RequestPaging {
  private final int pageSize;

  // List of property changes.
  private final ArrayList<PropertyChange> propertyChangeList;

  // Array index in the propertyChangeList from which next page should begin.
  private int currentReadIndex = 0;

  /**
   * Constructor for this class.
   *
   * @param propertyChangeList changes this class consists of.
   * @param pageSize size of each page.
   */
  public RequestPaging(ArrayList<PropertyChange> propertyChangeList,  int pageSize) {
    this.pageSize = pageSize;
    this.propertyChangeList = propertyChangeList;
  }

  /**
   * Get the page size.
   *
   * @return approximate size of each page returned by getNextChangeList();
   */
  public int getPageSize() {
    return pageSize;
  }

  /**
   * Get the next "page" as a set of property changes
   *
   * @return the next set of changes.
   */
  public ArrayList<PropertyChange> getNextChangeList() {
    ArrayList<PropertyChange> returnPage = new ArrayList<PropertyChange>();
    int size = 0;
    while (currentReadIndex < propertyChangeList.size()) {
      size += propertyChangeList.get(currentReadIndex).toString().length();
      if (size > pageSize && !returnPage.isEmpty()) {
        break;
      }

      returnPage.add(propertyChangeList.get(currentReadIndex));
      currentReadIndex++;
    }

    return returnPage;
  }

  /**
   * check whether this page has any more page to be returned.
   *
   * @return true if the it has more changes in the change list false otherwise.
   */
  public boolean hasNextChangeList() {
    return currentReadIndex < propertyChangeList.size();
  }

  /**
   * Clear changes in the Class.
   */
  public void clear() {
    propertyChangeList.clear();
    currentReadIndex = 0;
  }
}
